from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class PhoneNumber(models.Model):
  # Phone number, in format XXXXXXXXXX
  number = models.CharField(max_length=10)
  created = models.DateTimeField(auto_now_add=True)
  accessed = models.ManyToManyField(User, through='PhoneAccess')
  def __str__(self):
    # Prints phone number in format 555-555-5555
    return '(%s) %s-%s' % (self.number[0:3], self.number[3:6], self.number[6:10])
    
class PhoneAccess(models.Model):
  user = models.ForeignKey(User)
  number = models.ForeignKey(PhoneNumber)
  accessed = models.DateTimeField(auto_now_add=True)
  def __str__(self):
    return '%s accessed %s' % (self.user, self.number)

class UserProfile(models.Model):
  # A link to the native Django user object
  user = models.OneToOneField(User)
  # PhoneNumber entry
  number = models.ForeignKey(PhoneNumber, blank=True, null=True)
  # Have we verified that this user owns the phone? (By sending a text)
  verified = models.BooleanField(default=False)
  confirmation_code = models.CharField(max_length=15, blank=True, null=True)
  # When this was created
  created = models.DateTimeField(auto_now_add=True)
  # Last time the user logged in
  last_login = models.DateTimeField(auto_now=True)
  def __str__(self):
    if self.number:
      return '%s - %s' % (str(self.user), self.number)
    else:
      return str(self.user)

class Review(models.Model):
  """A single review, posted by a single user"""
  # The phone number this review refers to
  number = models.ForeignKey(PhoneNumber)
  # The user who posted this review
  user = models.ForeignKey(User)
  # Review content
  text = models.TextField()
  # Post date
  date = models.DateTimeField(auto_now_add=True)
  # Number of votes, cached
  votes = models.IntegerField(default=0)
  # Set of people who voted 
  vote_ups = models.ManyToManyField(User, related_name='vote_ups')
  vote_downs = models.ManyToManyField(User, related_name='vote_downs')
  # Invalid if deleted
  valid = models.BooleanField(default=True)
  
  def __str__(self):
    text = (self.text[:50] + '...') if len(self.text) > 50 else self.text
    return '%s: %s' % (self.user, text)
  
  def number_display(self):
    return '(%s)' % self.number.number[0:3]
    
  def poster_number_display(self):
    return '(%s)' % self.user.get_profile().number.number[0:3]
    
class Invite(models.Model):
  """An invite object.  An admin can generate invites, and its used by alpha/beta
  testers to sign up"""
  code = models.CharField(max_length=20)
  used = models.BooleanField(default=False)
  created = models.DateTimeField(auto_now_add=True)
  modified = models.DateTimeField(auto_now=True)
  user = models.ForeignKey(User, blank=True, null=True)
  
  def use(self, user):
    self.user = user
    self.used = True
    self.save()
  
  def __str__(self):
    if self.used:
      return 'Used invite by %s' % self.user.username
    else:
      return 'Unused invite: %s' % self.code


class MassInvite(models.Model):
  """An mass invite object.  An admin can generate invites, and its used by 
  alpha/beta testers to sign up.  Mass invites are allowed to be used more than once."""
  name = models.CharField(max_length=20)
  code = models.CharField(max_length=20)
  disabled = models.BooleanField(default=False)
  created = models.DateTimeField(auto_now_add=True)
  modified = models.DateTimeField(auto_now=True)
  users = models.ManyToManyField(User)
  
  def use(self, user):
    self.users.add(user)
    self.save()
  
  def __str__(self):
    if self.used:
      return 'Used invite %s by %d users' % (self.code, len(self.users))
    else:
      return 'Unused invite: %s' % self.code


class Feedback(models.Model):
  """A piece of feedback from someone"""
  # Type of feedback
  type = models.CharField(max_length=20, default='Unspecified')
  # The user who wrote it
  user = models.ForeignKey(User)
  # Feedback content
  text = models.TextField()
  # URL that they were directed from
  url = models.CharField(max_length=50)
  # Creation date
  created = models.DateTimeField(auto_now_add=True)
  
  def __str__(self):
    return '%s by %s' % (self.type, self.user)

class Activity(models.Model):
  """Caches recent activities"""
  description = models.CharField(max_length=50)
  user = models.ForeignKey(User, blank=True, null=True)
  created = models.DateTimeField(auto_now_add=True)
  
  def __str__(self):
    if self.user.get_profile():
      return '%s %s' % (self.user.get_profile().number, self.description)
    else:
      return '%s %s' % (self.user, self.description)
      
      
class Prospective(models.Model):
  """Where we store information on prospective users"""
  name = models.CharField(max_length=50)
  email = models.EmailField()
  referrer = models.CharField(max_length=50)
  created = models.DateTimeField(auto_now_add=True)
  invite = models.OneToOneField(Invite, null=True, blank=True)
  
class ProspectiveMessage(models.Model):
  """Email to send to prospectives"""
  subject = models.CharField(max_length=50)
  body = models.TextField()
  created = models.DateTimeField(auto_now_add=True)
  selected = models.BooleanField(default=False)

# Create UserProfile automatically after User is created
def create_user_profile(sender, instance, created, **kwargs):
  if created:
    UserProfile.objects.get_or_create(user=instance)

    
post_save.connect(create_user_profile, sender=User)
